const axios = require('axios')
const cheerio = require('cheerio')
const fs = require('fs')

export const fetchImages = async (url, save, load, done, crawl, crawlError) => {
  try {
    crawl()
    const { data } = await axios.get(url)
    const $ = cheerio.load(data)
    const images = $('img') // 选择所有图片
    load(images.length)
    let createArr = []
    images.each((index, image) => {
      const src = $(image).attr('src')
      if (src) {
        createArr.push(
          new Promise(async (resolve, reject) => {
            try {
              const response = await getImg(src)
              const imagePath = save + `/${index}.jpg`
              const writeStream = fs.createWriteStream(imagePath)
              response.data.pipe(writeStream)
              // 确认保存成功
              writeStream.on('finish', () => {
                resolve()
              })
              // 处理错误
              writeStream.on('error', (err) => {
                writeStream.end()
                reject(err)
              })
            } catch (e) {
              reject(e)
            }
          }),
        )
      }
    })
    Promise.allSettled(createArr)
      .then((res) => {
        done(res)
      })
      .catch((err) => {
        crawlError(err)
      })
  } catch (error) {
    crawlError(error)
  }
}
const getImg = (src) => {
  return new Promise((resolve, reject) => {
    axios
      .get(src, { responseType: 'stream' })
      .then((response) => {
        resolve(response)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
